package com.highper.common.sehcma;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.core.parser.SqlInfo;
import lombok.Data;
import lombok.experimental.Accessors;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Map;


/**
 * @Author ZhangGJ
 * @Date 2022/01/24 15:13
 */
@Data
@Accessors(chain = true)
public class DynamicTableNameParser implements ISqlParser {

    @Override
    public SqlInfo parser(MetaObject metaObject, String sql) {
        MultiTenantInterceptor multiTenantInterceptor = new MultiTenantInterceptor();
        multiTenantInterceptor.setSchemaName(ContextHandler.getSchema());
        String parsedSql = multiTenantInterceptor.processSqlByInterceptor(sql);
        return SqlInfo.newInstance().setSql(parsedSql);
    }

    /**
     * 勿删
     * @Author ZhangGJ
     * @param args
     */
    public static void main(String[] args) {
        MultiTenantInterceptor multiTenantInterceptor = new MultiTenantInterceptor();
        multiTenantInterceptor.setSchemaName("jjccb");
        String result = multiTenantInterceptor.processSqlByInterceptor("MERGE INTO assets USING ( SELECT A.ID AS aid, U.NAME, U.USERNAME, U.EMAIL, U.PHONE FROM assets A, USERS U WHERE JSON_VALUE ( A.asset_attributes, '$.usepeoper.value' ) = U.ID AND JSON_VALUE ( A.asset_attributes, '$.usepeoper.value' ) = 1 ) U ON ( assets.id = U.aid ) \n"
                + "WHEN MATCHED THEN\n" + "UPDATE \n"
                + "\tSET assets.asset_attributes = OF_JSON_SET (\n" + "\t\tOF_JSON_SET (\n"
                + "\t\t\tOF_JSON_SET ( OF_JSON_SET ( OF_JSON_SET ( OF_JSON_SET ( OF_JSON_SET ( asset_attributes, '$.usepeoper.text', U.NAME ), '$.phone.value', U.USERNAME ), '$.phone.text', U.USERNAME ), '$.email.text', NVL( U.EMAIL, NULL ) ), '$.email.value', NVL( U.EMAIL, NULL ) ),\n"
                + "\t\t\t'$.tel.text',\n" + "\t\t\tNVL( U.PHONE, NULL ) \n" + "\t\t),\n"
                + "\t\t'$.tel.value',\n" + "\tNVL( U.PHONE, NULL ) \n" + "\t);");
        System.out.println(result);
    }
}
